import storage from 'good-storage'

const SEARCH_KEY = '__search__'
const SEARCH_MAX_LEN = 15

const PLAY_KEY = '_play_'
const PlAY_MAX_LEN = 200

const FAVORITE_KEY = '_favorite_'
const FAVORITE_MAX_LEN = 200

function insertArray(arr, val, compare, maxLen) {
  const index = arr.findIndex(compare)

  if(index === 0){
    return
  }
  if(index > 0){
    arr.splice(index, 1)
  }
  arr.unshift(val)
  if (maxLen && arr.length > maxLen) {
    arr.pop()
  }
}

function deleteFromArray(arr, compare) {
  const index = arr.findIndex(compare)
  if(index > -1){
    arr.splice(index,1)
  }
}

export function saveSearch(query){
  let searches = storage.get(SEARCH_KEY, [])
  insertArray(searches, query, (item) => {
    return item === query
  },SEARCH_MAX_LEN)
  storage.set(SEARCH_KEY, searches)
  return searches
}

export function deleteSearch(query) {
  let searches = storage.get(SEARCH_KEY, [])

  deleteFromArray(searches, (item) => {
    return item === query
  })
  storage.set(SEARCH_KEY, searches)

  return searches
}

export function clearSearch() {
  storage.set(SEARCH_KEY, [])
  return []
}

export function loadSearch(){
  return storage.get(SEARCH_KEY, [])
}

export function savePlay(song) {
  const playes = storage.get(PLAY_KEY, [])
  insertArray(playes, song, (item) => {
    return item.id === song.id
  }, PlAY_MAX_LEN)
  console.info(playes)
  storage.set(PLAY_KEY, playes)
  return playes
}

export function loadPlay() {
 return storage.get(PLAY_KEY, [])
}

export function saveFavorite(song) {
  let songs = storage.get(FAVORITE_KEY, [])
  insertArray(songs, song, (item) => {
    return item.id === song.id
  })
  storage.set(FAVORITE_KEY, songs)
  return songs
}

export function deleteFavorite(song) {
  let songs = storage.get(FAVORITE_KEY, [])

  deleteFromArray(songs, (item) => {
    return item.id === song.id
  })
  storage.set(FAVORITE_KEY, songs)

  return songs
}

export function loadFavorite() {
  return storage.get(FAVORITE_KEY, [])
}


